package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Destination;

import cn.wolfcode.wolf2w.business.api.domain.Region;
import cn.wolfcode.wolf2w.business.mapper.DestinationMapper;
import cn.wolfcode.wolf2w.business.mapper.RegionMapper;
import cn.wolfcode.wolf2w.business.query.DestinationQuery;
import cn.wolfcode.wolf2w.business.service.IDestinationService;
import cn.wolfcode.wolf2w.business.service.IRegionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * 目的地Service业务层处理
 *
 * @author zty
 * @date 2025-09-16
 */
@Service
@Transactional
public class DestinationServiceImpl extends ServiceImpl<DestinationMapper, Destination> implements IDestinationService {
    @Autowired
    private IRegionService regionService;
    @Resource
    private RegionMapper regionMapper;

    @Override
    public IPage<Destination> queryPage(DestinationQuery qo) {
        IPage<Destination> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public List<Map<String, Object>> search(Integer regionId) {

        // 一级目的地列表
        List<Destination> list = lambdaQuery()
                .eq(Destination::getRegionId, regionId)
                .list();

        //二级目的地的列表
        List<Destination> secondLevelList = new ArrayList<>();
        // 三级目的地的列表
        List<Destination> thirdLevelList = new ArrayList<>();
        // 二-三映射关系
        Map<Destination, List<Destination>> secondToThirdMap = new HashMap<>();
        //一-二映射关系
        Map<Destination, List<Destination>> FirstToSecondMap = new HashMap<>();
        if (regionId < 0) {
            // 遍历一级目的地，获取它们的二级子目的地
            for (Destination firstLevel : list) {
                List<Destination> secondLevelDestinations = lambdaQuery()
                        .eq(Destination::getParentId, firstLevel.getId())
                        .list();
                secondLevelList.addAll(secondLevelDestinations);

            }
            // 构建一级目的地到二级目的地的映射关系
            for (Destination Level : list) {
                List<Destination> children = new ArrayList<>();
                for (Destination secondLevel : secondLevelList) {
                    // 如果三级目的地的父ID等于当前二级目的地的ID，则建立父子关系
                    if (Level.getId().equals(secondLevel.getParentId())) {
                        children.add(secondLevel);
                    }
                }
                FirstToSecondMap.put(Level, children);
            }

            // 遍历二级目的地，获取它们的三级子目的地
            for (Destination secondLevel : secondLevelList) {
                List<Destination> thirdLevelDestinations = lambdaQuery()
                        .eq(Destination::getParentId, secondLevel.getId())
                        .list();
                thirdLevelList.addAll(thirdLevelDestinations);
            }


            /*如果没有三级路径，就构造一二级关系*/
            // 构建最终返回的结果列表，每个元素包含二级目的地信息及其子目的地列表
            List<Map<String, Object>> finalResult = new ArrayList<>();
         /*   for (Map.Entry<Destination, List<Destination>> entry : FirstToSecondMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                // 添加一级目的地的ID
                item.put("id", entry.getKey().getId());
                // 添加一级目的地的名称
                item.put("name", entry.getKey().getName());
                // 添加该一级目的地下的二级目的地列表
                item.put("children", entry.getValue());
                finalResult.add(item);
            }*/
            /*如果有三级路径就构造二三级关系*/
            // 构建二级目的地到三级目的地的映射关系
            for (Destination secondLevel : secondLevelList) {
                List<Destination> children = new ArrayList<>();
                for (Destination thirdLevel : thirdLevelList) {
                    // 如果三级目的地的父ID等于当前二级目的地的ID，则建立父子关系
                    if (secondLevel.getId().equals(thirdLevel.getParentId())) {
                        children.add(thirdLevel);
                    }
                }
                secondToThirdMap.put(secondLevel, children);
            }

            for (Map.Entry<Destination, List<Destination>> entry : secondToThirdMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                // 添加二级目的地的ID
                item.put("id", entry.getKey().getId());
                // 添加二级目的地的名称
                item.put("name", entry.getKey().getName());
                // 添加该二级目的地下的三级目的地列表
                item.put("children", entry.getValue());
                finalResult.add(item);
            }
            return finalResult;


        } else {
            // 一级目的地列表
            List<Destination> firstList = new ArrayList<>();

            Region region = regionService.getById(regionId);
            String refIds = region.getRefIds();
            String[] idArray = refIds.split(",");
            int[] numbers = new int[idArray.length];
            for (int i = 0; i < idArray.length; i++) {
                numbers[i] = Integer.parseInt(idArray[i]);
            }

            for (
                    int i = 0; i < numbers.length; i++
            ) {
                Destination destination = getById(numbers[i]);
                firstList.add(destination);
            }

            for (int i = 0; i < numbers.length; i++) {
                List<Destination> secondLevelDestinations = lambdaQuery().eq(Destination::getParentId, numbers[i]).list();
                secondLevelList.addAll(secondLevelDestinations);

            }
            // 构建一级目的地到二级目的地的映射关系
            for (Destination Level : firstList) {
                List<Destination> children = new ArrayList<>();
                for (Destination secondLevel : secondLevelList) {
                    // 如果三级目的地的父ID等于当前二级目的地的ID，则建立父子关系
                    if (Level.getId().equals(secondLevel.getParentId())) {
                        children.add(secondLevel);
                    }
                }
                FirstToSecondMap.put(Level, children);
            }
            /*如果没有三级路径，就构造一二级关系*/
            // 构建最终返回的结果列表，每个元素包含二级目的地信息及其子目的地列表
            List<Map<String, Object>> finalResult = new ArrayList<>();
            for (Map.Entry<Destination, List<Destination>> entry : FirstToSecondMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                // 添加一级目的地的ID
                item.put("id", entry.getKey().getId());
                // 添加一级目的地的名称
                item.put("name", entry.getKey().getName());
                // 添加该一级目的地下的二级目的地列表
                item.put("children", entry.getValue());
                finalResult.add(item);
            }
            return finalResult;


        }
    }

    @Override
    public List<Destination> queryByRegionId(Long regionId) {
        List<Destination> list= null;
        if (regionId>0){
            //国外
            Region region = regionMapper.selectById(regionId);
            String refIds = region.getRefIds();
            String[] split = refIds.split(",");
            list = new ArrayList<>();
            for (String string : split) {
                Long id=Long.valueOf(string);
                //baseMapper
                Destination destination = baseMapper.selectById(id);

                list.add(destination);
            }

        }else{
            //国内
           list = lambdaQuery().eq(Destination::getParentId, 1).list();

        }
        //查询二级数据
        for (Destination destination : list){
            //遍历取前十
            List<Destination> secondLevel = lambdaQuery().eq(Destination::getParentId, destination.getId()).last("limit 10").list();
            destination.setChildren(secondLevel);

        }
        return list ;
    }

    @Override
    public List<Destination> queryToasts(Long destId) {

        /*核心：递归*/
      List<Destination> list = new ArrayList<>();
      createToasts(destId,list);
      //反序输出
      //Collections.reverse(list);
      return list;
    }

    private void createToasts(Long destId, List<Destination> list){
            if (destId==null){
                return;
            }
            Destination destination = baseMapper.selectById(destId);

            createToasts(destination.getParentId(),list);
            //回溯
            list.add(destination);
    }



}
